﻿using DDD.Core;
using DDD.Domain;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace DDD.EFCore
{
    public static class MediatorExtension
    {
        public static async Task DispatchDomainEventsAsync(this IMediator mediator, DbContext ctx)
        {
            var domainEntities = ctx.ChangeTracker.Entries<Entity>().Where(e => e.Entity.DomainEvents.Any());
            var domainEvents = ctx.ChangeTracker.Entries<Entity>().SelectMany(e => e.Entity.DomainEvents).ToList();
            try
            {
                foreach (var @event in domainEvents)
                {
                    await mediator.Publish(@event);
                }
            }
            finally
            {
                foreach (var @entity in domainEntities)
                {
                    entity.Entity.ClearDomainEvent();
                }
            }
        }
    }
}
